$(function(){
	/*
	 * 开局时间 datapicker 初始化
	 */
	var curDate = new Date();
	var nextThreeDate = new Date();
	var nextThirtyDate = new Date();
	nextThreeDate.setDate(curDate.getDate() + 3);
	nextThirtyDate.setDate(curDate.getDate() + 30);
	$('#gather-start-time').datetimepicker({
		dayViewHeaderFormat: 'YYYY MMMM',
		locale: 'zh-cn',
		format: 'YYYY-MM-DD HH:mm',
		keepInvalid: true,
		minDate: nextThreeDate, 
		maxDate: nextThirtyDate 
	});	 


	/*
	 * 初始化行业选择 modal
	 */
	$('#industry-select-modal').modal({
		backdrop: 'static',
		keyboard: false,	
		show: false
	});

	var $insModal = $('#industry-select-modal');

	/*
	 * 行业选择器
	 */
	function IndustryTager() {
		var self = this;
		this.$modal = $('#industry-select-modal');
		this.$selectedTagContainer = $('#industry-tag-container');
		this.tagEleMap = {};
		this.$msgBox = $('.msg',this.$modal).html('最多选择2个行业').hide();
		$('.confirm-btn',this.$modal).on('click',function(){
			self._confirm();
		});

		$('.tag-box :checkbox',this.$modal).each(function(){
			var key = $(this).next().html();
			self.tagEleMap[key] = $(this);
		});
		/*
		 * 初始化 icheck
		 */
		$('input').iCheck({
			checkboxClass: 'icheckbox_flat-orange',
			radioClass: 'iradio_flat-orange'
		});
		this._init();
	}

	IndustryTager.prototype = {
		constructor : IndustryTager,
		$selectedTagContainer: null,
		tagLimit: 2,
		$modal: null,
		$msgBox: null,
		tagEleMap: null,
		open: function() {
			this.$modal.modal('show');
		},
		hide: function() {
			this.$modal.modal('hide');
		},
		getData: function() {
			var industryTag = [];
			$('a',this.$selectedTagContainer).each(function(){
				industryTag.push($(this).html());	
			});
			return industryTag.toString();
		},
		_confirm: function() {
			var self = this;
			var $tagChecked = $(':checked',this.$modal);	
			if($tagChecked.length > this.tagLimit) {
				this.$msgBox.slideDown();
			} else {
				this.$msgBox.slideUp();
				this.$selectedTagContainer.empty();
				$tagChecked.each(function(){
					var $this = $(this);
					var $tag = $('<a class="label label-primary">'+$this.parent().next().html()+'</a>');
					self.$selectedTagContainer.append($tag);	
				});
				this.$modal.modal('hide');
			}
		},
		_init: function() {
			var self = this;
			var selectedTags = [];				
			$('.label',this.$selectedTagContainer).each(function(){
				selectedTags.push($(this).html());
			});
			for(var index in selectedTags) {
				var $checkbox = self.tagEleMap[selectedTags[index]];
				if($checkbox != undefined) {
					$checkbox.iCheck('check');
				}
			}	
		}
	};

	var tager = new IndustryTager();

	/*
	 * 初始化 错误提示
	 */

	$('#industry-select-btn').on('click',function(){
		tager.open();
	});

	$('.cancel-btn',$insModal).on('click',function(){
		tager.hide();
	});

	/*
	 * 表单验证错误 显示/隐藏
	 */
	function toggleError(show,ele,msg) {
		if(ele.next().length == 0) {
			ele.after('<label class="err-label"><i class="fa fa-times-circle-o"></i><span></span></label>');
		}
		if(show) {
			ele.next().show().find('span').html(msg);
			ele.parent().addClass('has-error');
		} else {
			ele.parent().removeClass('has-error');
			ele.next().hide();
		}
	}

	/*
	 * 表单验证
	 */
	$('#gather-form').validate({
		rules: {
			theme: {
			    required: true,
				maxlength: 20 
		    },
			desc: {
				required: true,
				maxlength: 500 
			},
			invnum: {
				required: true,
				digits: true,
				min: 1,
				max: 30 
			},
			kickback: {
				required: true,
				number: true
			}
					   	   
	    },
		showErrors: function(errorMap, errorList){
						console.log(errorMap);
						console.log(errorList);
						if(errorList.length == 0) {
							return;	
						} else {
							var msg = '',
								curEle,
								eleName;
							if(errorList.length > 0) {
								var err = errorList[0],
									curEle = $(err.element);
									eleName = curEle.prev().html();
								if(err.method == 'required') {
									msg = eleName+"不能为空";
								} else if(err.method == 'maxlength') {
									switch(curEle.attr('name')) {
										case 'theme':
											msg = eleName + '不能超过20个字';
										break;
										case 'desc': 
											msg = eleName + '不能超过500个字';
										break;
									}
								} else if(err.method == 'digits') {
									msg = '请输入整数';
								} else if(err.method == 'number') {
									msg = '请输入正确的金额格式';
								} else if(err.method == 'min') {
									msg = '邀请人数最少为1人';
								} else if(err.method == 'max') {
									msg = '邀请人数最多为30人';
								}
							}
							toggleError(true,curEle,msg);
						}
					},
		submitHandler: function(){
					   save();
				   },
		onkeyup: function(ele) {
			toggleError(false,$(ele));
		}
	});

	$('#save-btn').on('click',function(){
		$('#gather-form').submit();
	});

	var $loading = $('.overlay').hide();
	function save() {
		$loading.show();
		var data = {
			id: $('#gather-id').val(),
			theme: $('#gather-title').val(),
			description: $('#gather-desc').val(),
			startTime: $('#gather-start-time').val(),
			duration: $('#gather-duration').val(),
			maxNum: $('#gather-invited-num').val(),
			kickback: $('#gather-kickback').val()
		};

		data['industry'] = tager.getData();
			
		cAjax({
			url: '/gather/gathering/gather/edit',
			data: data,
			success: function(obj) {
				$loading.hide();
				greeting({
					msg: '约局保存成功'
				});
			}
		});
	}

});
